package com.example.studyPlatform.controller;

import com.example.studyPlatform.bean.User;
import com.example.studyPlatform.config.ThemeConfig;
import com.example.studyPlatform.controller.api.protocol.UUIDWebSocket;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpSession;

import static com.example.studyPlatform.config.BaseConstant.MSG;
import static com.example.studyPlatform.config.BaseConstant.USR;
import static com.example.studyPlatform.config.RoutingConstant.*;
import static com.example.studyPlatform.controller.api.kit.JsonUtils.objectToString;

@Controller
public class QRCodeController {
    ThemeConfig themeConfig;
    UUIDWebSocket QRWebSocket;

    public QRCodeController(ThemeConfig themeConfig, UUIDWebSocket QRWebSocket) {
        this.themeConfig = themeConfig;
        this.QRWebSocket = QRWebSocket;
    }

    // 回调
    @GetMapping(QR_LOGIN + "/{uuid}")
    String viewQRCode(@PathVariable("uuid") String uuid, HttpSession session, Model model) {
        User user = (User) session.getAttribute(USR);
        if (user != null) {
            QRWebSocket.callback(uuid, objectToString(user));
            return themeConfig.render(USER_INDEX);
        } else {
            user=new User();
            user.setId(-1);
            QRWebSocket.callback(uuid, objectToString(user));
            model.addAttribute(MSG, "请先登录");
            return themeConfig.render(LOGIN);
        }
    }

}
